// app/vendor/quotations/page.tsx
import * as React from "react";
import Link from "next/link";
import { Metadata } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { LogIn } from "lucide-react";
import { DataTableSkeleton } from "@/components/data-table/data-table-skeleton";
import { Shell } from "@/components/shell";
import { getValidFilters } from "@/lib/data-table";
import { type SearchParams } from "@/types/table";
import { searchParamsVendorRfqCache } from "@/lib/procurement-rfqs/validations";
import { getQuotationStatusCounts, getVendorQuotations } from "@/lib/procurement-rfqs/services";
import { VendorQuotationsTable } from "@/lib/procurement-rfqs/vendor-response/table/vendor-quotations-table";
import { InformationButton } from "@/components/information/information-button"
export const metadata: Metadata = {
  title: "견적 목록",
  description: "진행 중인 견적서 목록",
};

interface IndexPageProps {
  searchParams: Promise<SearchParams>
}


export default async function  IndexPage(props: IndexPageProps) {
  const searchParams = await props.searchParams
  const search = searchParamsVendorRfqCache.parse(searchParams)
  const validFilters = getValidFilters(search.filters)
  // 인증 확인
  const session = await getServerSession(authOptions);
  
  // 로그인 확인
  if (!session || !session.user) {
    return (
      <Shell className="gap-6">
        <div className="flex items-center justify-between">
          <div>
            <div className="flex items-center gap-2">
              <h2 className="text-2xl font-bold tracking-tight">
                견적 목록
              </h2>
              <InformationButton pagePath="partners/rfq-ship" />
            </div>
            {/* <p className="text-muted-foreground">
              진행 중인 견적서 목록을 확인하고 관리합니다.
            </p> */}
          </div>
        </div>

        <div className="flex flex-col items-center justify-center py-12 text-center">
          <div className="rounded-lg border border-dashed p-10 shadow-sm">
            <h3 className="mb-2 text-xl font-semibold">로그인이 필요합니다</h3>
            <p className="mb-6 text-muted-foreground">
              견적서를 확인하려면 먼저 로그인하세요.
            </p>
            <Button size="lg" asChild>
              <Link href="/partners?callbackUrl=/vendor/quotations">
                <LogIn className="mr-2 h-4 w-4" />
                로그인하기
              </Link>
            </Button>
          </div>
        </div>
      </Shell>
    );
  }
  
  // 벤더 ID 확인
  const vendorId = session.user.companyId ? String(session.user.companyId) : "0";
  
  // 벤더 권한 확인
  if (session.user.domain !== "partners") {
    return (
      <Shell className="gap-6">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-bold tracking-tight">
              접근 권한 없음
            </h2>
          </div>
        </div>
        <div className="flex flex-col items-center justify-center py-12 text-center">
          <div className="rounded-lg border border-dashed p-10 shadow-sm">
            <h3 className="mb-2 text-xl font-semibold">벤더 계정이 필요합니다</h3>
            <p className="mb-6 text-muted-foreground">
              벤더 계정으로 로그인해주세요.
            </p>
          </div>
        </div>
      </Shell>
    );
  }
  
  // 데이터 가져오기
  const quotationsPromise = getVendorQuotations({
    ...search,
    filters: validFilters
  }, vendorId);
  
  // 상태별 개수 가져오기
  const statusCountsPromise = getQuotationStatusCounts(vendorId);
  
  // 모든 프로미스 병렬 실행
  const promises = Promise.all([quotationsPromise]);
  const statusCounts = await statusCountsPromise;
  
  return (
    <Shell className="gap-6">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">견적 목록</h2>
          <p className="text-muted-foreground">
            진행 중인 견적서 목록을 확인하고 관리합니다.
          </p>
        </div>
      </div>
      
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="py-4">
            <CardTitle className="text-base">전체 견적</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {Object.values(statusCounts).reduce((sum, count) => sum + count, 0)}건
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="py-4">
            <CardTitle className="text-base">작성 중</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{statusCounts.Draft || 0}건</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="py-4">
            <CardTitle className="text-base">제출됨</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {(statusCounts.Submitted || 0) + (statusCounts.Revised || 0)}건
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="py-4">
            <CardTitle className="text-base">승인됨</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{statusCounts.Accepted || 0}건</div>
          </CardContent>
        </Card>
      </div>
      
      <React.Suspense
        fallback={
          <DataTableSkeleton
            columnCount={7}
            searchableColumnCount={2}
            filterableColumnCount={3}
            cellWidths={["10rem", "10rem", "8rem", "10rem", "10rem", "10rem", "8rem"]}
          />
        }
      >
        <VendorQuotationsTable promises={promises} />
      </React.Suspense>
    </Shell>
  );
}